# ESP32 Calendar Application Toolkit
# Integrated environment activation, build, flash, monitor functions

param(
    [string]$Action = "help",
    [string]$Port = "",
    [switch]$Clean = $false
)

# Core configuration
$IDF_BASE_PATH = "D:\Sofwear\Espressif"
$IDF_VERSION = "v5.5.1"
$PYTHON_ENV = "idf5.5_py3.11_env"

# Environment paths
$env:IDF_PATH = "$IDF_BASE_PATH\frameworks\esp-idf-$IDF_VERSION"
$env:IDF_TOOLS_PATH = $IDF_BASE_PATH
$env:IDF_PYTHON_ENV_PATH = "$IDF_BASE_PATH\python_env\$PYTHON_ENV"

# Toolchain paths
$ToolPaths = @(
    "$IDF_BASE_PATH\tools\xtensa-esp-elf\esp-14.2.0_20241119\xtensa-esp-elf\bin",
    "$IDF_BASE_PATH\tools\cmake\3.30.2\bin",
    "$IDF_BASE_PATH\tools\ninja\1.12.1",
    "$IDF_BASE_PATH\python_env\$PYTHON_ENV\Scripts"
)

# Python paths
$IDF_PYTHON = "$IDF_BASE_PATH\python_env\$PYTHON_ENV\Scripts\python.exe"
$IDF_PY = "$IDF_BASE_PATH\frameworks\esp-idf-$IDF_VERSION\tools\idf.py"

function Write-Header {
    param([string]$Title)
    Write-Host ""
    Write-Host "[TITLE] $Title" -ForegroundColor Green
    Write-Host "=" * 50 -ForegroundColor Green
}

function Write-Success {
    param([string]$Message)
    Write-Host "[SUCCESS] $Message" -ForegroundColor Green
}

function Write-Error {
    param([string]$Message)
    Write-Host "[ERROR] $Message" -ForegroundColor Red
}

function Write-Info {
    param([string]$Message)
    Write-Host "[INFO] $Message" -ForegroundColor Cyan
}

function Get-AvailablePorts {
    Write-Header "Detecting Available Serial Ports"
    
    $Ports = Get-PnpDevice -Class Ports | Where-Object {$_.Status -eq 'OK'} | Select-Object FriendlyName, InstanceId
    
    if ($Ports.Count -eq 0) {
        Write-Error "No serial ports detected. Please check:"
        Write-Host "  1. ESP32 board is connected via USB" -ForegroundColor Yellow
        Write-Host "  2. CH340C driver is properly installed" -ForegroundColor Yellow
        Write-Host "  3. Device Manager shows 'USB-SERIAL CH340'" -ForegroundColor Yellow
        return $null
    }
    
    Write-Host "Available serial ports:" -ForegroundColor Cyan
    foreach ($Port in $Ports) {
        Write-Host "  PORT: $($Port.FriendlyName)" -ForegroundColor Green
    }
    
    # Auto-detect CH340 port
    $CH340Port = $Ports | Where-Object {$_.FriendlyName -like "*CH340*"}
    if ($CH340Port) {
        $PortName = ($CH340Port.FriendlyName -split "\(" | Select-Object -Last 1) -replace "\)", ""
        Write-Success "CH340 device detected: $PortName"
        return $PortName
    }
    
    return $null
}

function Initialize-Environment {
    Write-Header "Initializing ESP-IDF Environment"
    
    if (-not (Test-Path $IDF_PYTHON)) {
        Write-Error "Python environment not found"
        exit 1
    }
    
    if (-not (Test-Path $IDF_PY)) {
        Write-Error "idf.py tool not found"
        exit 1
    }
    
    foreach ($Path in $ToolPaths) {
        if (Test-Path $Path) {
            $env:PATH = "$Path;" + $env:PATH
        }
    }
    
    Write-Success "Environment initialized successfully"
}

function Invoke-Clean {
    Write-Header "Cleaning Build Files"
    & $IDF_PYTHON $IDF_PY fullclean
    if ($LASTEXITCODE -eq 0) {
        Write-Success "Clean completed"
    } else {
        Write-Error "Clean failed"
        exit 1
    }
}

function Invoke-Build {
    Write-Header "Building ESP32 Calendar Application"
    
    if ($Clean) {
        Invoke-Clean
    }
    
    & $IDF_PYTHON $IDF_PY build
    
    if ($LASTEXITCODE -eq 0) {
        Write-Success "Build successful"
        
        $BinFile = "build\calendar.bin"
        if (Test-Path $BinFile) {
            $FileInfo = Get-Item $BinFile
            $FileSizeKB = [math]::Round($FileInfo.Length/1024, 2)
            Write-Host "FILE: Binary file: $($FileInfo.Name)" -ForegroundColor Cyan
            Write-Host "SIZE: File size: $FileSizeKB KB" -ForegroundColor Cyan
            Write-Host "SPACE: Available space: 83%" -ForegroundColor Cyan
        }
    } else {
        Write-Error "Build failed"
        exit 1
    }
}

function Invoke-Flash {
    param([string]$TargetPort = $Port)
    
    Write-Header "Flashing to Development Board"
    
    if (-not $TargetPort) {
        $TargetPort = Get-AvailablePorts
        if (-not $TargetPort) {
            Write-Error "No CH340 device detected. Please specify port manually with -Port parameter"
            exit 1
        }
    }
    
    Write-Info "Using port: $TargetPort"
    & $IDF_PYTHON $IDF_PY -p $TargetPort flash
    
    if ($LASTEXITCODE -eq 0) {
        Write-Success "Flash successful"
    } else {
        Write-Error "Flash failed. Please check:"
        Write-Host "  1. ESP32 board is in bootloader mode (hold BOOT button while connecting)" -ForegroundColor Yellow
        Write-Host "  2. Correct COM port is selected" -ForegroundColor Yellow
        Write-Host "  3. No other program is using the serial port" -ForegroundColor Yellow
        exit 1
    }
}

function Invoke-Monitor {
    param([string]$TargetPort = $Port)
    
    Write-Header "Starting Serial Monitor"
    
    if (-not $TargetPort) {
        $TargetPort = Get-AvailablePorts
        if (-not $TargetPort) {
            Write-Error "No CH340 device detected. Please specify port manually with -Port parameter"
            exit 1
        }
    }
    
    Write-Info "Monitoring port: $TargetPort"
    Write-Host "Press Ctrl+] to exit monitor" -ForegroundColor Yellow
    & $IDF_PYTHON $IDF_PY -p $TargetPort monitor
}

function Show-Help {
    Write-Header "ESP32 Calendar Application Toolkit"
    Write-Host "Usage:" -ForegroundColor Cyan
    Write-Host "  .\esp32_toolkit.ps1 [action] [parameters]"
    Write-Host ""
    Write-Host "Available actions:" -ForegroundColor Cyan
    Write-Host "  help                    Show this help"
    Write-Host "  build [-Clean]          Build the project"
    Write-Host "  flash [-Port COMx]     Flash to board"
    Write-Host "  monitor [-Port COMx]   Start serial monitor"
    Write-Host "  build-flash             Build and flash"
    Write-Host "  clean                   Clean build files"
    Write-Host ""
}

# Main program
Write-Host ""
Write-Host "ESP32 Calendar Application Toolkit" -ForegroundColor Magenta
Write-Host "=" * 50 -ForegroundColor Magenta

Initialize-Environment

switch ($Action.ToLower()) {
    "help" {
        Show-Help
    }
    "clean" {
        Invoke-Clean
    }
    "build" {
        Invoke-Build
    }
    "flash" {
        Invoke-Flash
    }
    "monitor" {
        Invoke-Monitor
    }
    "build-flash" {
        Invoke-Build
        if ($LASTEXITCODE -eq 0) {
            Invoke-Flash
        }
    }
    default {
        Write-Error "Unknown action: $Action"
        Show-Help
        exit 1
    }
}

Write-Host ""
Write-Host "Operation completed!" -ForegroundColor Green